

package com.kimo.shop.user.admin.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.bean.enums.OrderStatus;
import com.kimo.shop.bean.enums.OrderType;
import com.kimo.shop.bean.enums.RefundStatusEnum;
import com.kimo.shop.bean.model.Order;
import com.kimo.shop.bean.model.OrderItem;
import com.kimo.shop.bean.model.UserAddrOrder;
import com.kimo.shop.bean.param.DeliveryOrderParam;
import com.kimo.shop.bean.param.OrderParam;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.i18n.I18nMessage;
import com.kimo.shop.common.i18n.LanguageEnum;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author kimo-taozhouchuan on 2018/09/15.
 */
@Controller
@RequestMapping("/score/order")
@RequiredArgsConstructor
public class ScoreOrderController {

    @Value("${kimo.expose.permission:}")
    private Boolean permission;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private OrderExcelService orderExcelService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Order>> page(OrderParam orderParam,PageParam<Order> page) {
        orderParam.setShopId(Constant.PLATFORM_SHOP_ID);
        orderParam.setOrderType(OrderType.SCORE.value());
        orderParam.setLang(I18nMessage.getDbLang());
        IPage<Order> orderIPage = orderService.pageOrdersDetialByOrderParam(page, orderParam);
        for (Order order : orderIPage.getRecords()) {
            if(StrUtil.isBlank(order.getShopName())){
                order.setShopName(Constant.PLATFORM_SHOP_NAME);
            }
            if (BooleanUtil.isFalse(permission)){
                UserAddrOrder userAddrOrder = order.getUserAddrOrder();
                userAddrOrder.setMobile(PhoneUtil.hideBetween(userAddrOrder.getMobile()).toString());
            }
        }
        return ResponseEntity.ok(orderIPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/orderInfo/{orderNumber}")
    public ResponseEntity<Order> info(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = Constant.PLATFORM_SHOP_ID;
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber,shopId,true);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber, I18nMessage.getDbLang());
        order.setOrderItems(orderItems);
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        return ResponseEntity.ok(order);
    }

    /**
     * 发货
     */
    @PutMapping("/delivery")
    public ResponseEntity<Void> delivery(@RequestBody DeliveryOrderParam deliveryOrderParam) {
        Long shopId = Constant.PLATFORM_SHOP_ID;
        Order order = orderService.getOrderByOrderNumberAndShopId(deliveryOrderParam.getOrderNumber(),shopId,true);

        if (Objects.equals(order.getRefundStatus(), RefundStatusEnum.APPLY.value())) {
            // 该订单有退款信息正在处理当中，请处理完毕之后再进行发货的操作
            throw new KimoShopBindException("kimo.order.delivery.refund.error");
        }
        if (!Objects.equals(order.getStatus(), OrderStatus.PADYED.value())){
            // 订单不处于待发货状态，无法进行发货
            throw new KimoShopBindException("kimo.order.delivery.no.right");
        }

        Order orderParam = new Order();
        orderParam.setOrderId(order.getOrderId());
        orderParam.setDvyId(deliveryOrderParam.getDvyId());
        orderParam.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
        orderParam.setDvyTime(new Date());
        orderParam.setUpdateTime(new Date());
        orderParam.setStatus(OrderStatus.CONSIGNMENT.value());
        orderParam.setUserId(order.getUserId());

        orderService.delivery(orderParam);

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(deliveryOrderParam.getOrderNumber(), I18nMessage.getDbLang());
        for (OrderItem orderItem : orderItems) {
            productService.removeProdCacheByProdId(orderItem.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
            productService.removeProdCacheByProdId(orderItem.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 已销售订单
     *
     * @param orderParam
     */
    @GetMapping("/soldExcel")
    public void soldExcel(OrderParam orderParam, HttpServletResponse response) {
        orderExcelService.soldExcel(orderParam,response);
    }
}
